package com.online.robot.wechat.controller;

import com.online.robot.wechat.builder.TextBuilder;
import com.online.robot.wechat.helper.WechatMpHelper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpKefuServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = {"/{appid}"})
public class WechatController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WechatMpHelper wechatMpHelper;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        logger.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
                timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        final WxMpService wxService = wechatMpHelper.getService(appid);
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam(name = "timestamp", required = false) String timestamp,
                       @RequestParam(name = "nonce", required = false) String nonce,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        logger.info("接收微信请求：[signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], \nrequestBody=[{}] ",
                signature, encType, msgSignature, timestamp, nonce, requestBody);
        final WxMpService wxService = wechatMpHelper.getService(appid);
        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = route(inMessage, appid);
            if (outMessage == null) {
                return new TextBuilder().build("请求结束,请重试", inMessage).toXml();
            }
            out = outMessage.toXml();
        } else if ("aes".equals(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            logger.info("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = route(inMessage, appid);
            if (outMessage == null) {
                return new TextBuilder().build("请求结束,请重试", inMessage).toXml();
            }
            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }
        logger.info("\n组装回复信息：{}", out);
        return out;
    }

    @GetMapping(value = {"/test"})
    public String test(String data) {
        logger.info("接受信息：{}", data);
        return "测试";
    }

    /**
     * 主动回复接口 需要微信认证后权限
     *
     * @param fromUser
     * @param weixinService
     * @param content
     */
    private void sendTextMessage(String fromUser, WxMpService weixinService, String content) {
        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.TEXT);
        message.setContent(content);
        message.setToUser(fromUser);
        WxMpKefuService wxMpKefuService = new WxMpKefuServiceImpl(weixinService);
        try {
            wxMpKefuService.sendKefuMessage(message);
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            e.printStackTrace();
        }
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message, String appid) {
        try {
            logger.info("route start");
            return wechatMpHelper.getRouter(appid).route(message);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            logger.info("route end");
        }
        return null;
    }
}
